package com.bestv.c2.handler;

import com.bestv.dao.helper.JDBCHelper;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;

/**
 * Created by Henry on 14-7-16.
 */
public class DumpHandler extends Handler {
    private String dumpSqlFormat;
    private String table;

    @Override
    public void handle() throws IOException, ParseException {
        File output = new File(outputPath);
        exportFile = new File(output, String.format("%s.csv", table));
        FileWriter file = new FileWriter(exportFile);
        BufferedWriter out = new BufferedWriter(file);

        String sql = String.format(dumpSqlFormat, table);
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            exportHead(rs, out);
            exportData(rs, out);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCHelper.close(rs);
            JDBCHelper.close(stmt);
            JDBCHelper.close(conn);
        }
        out.close();
    }

    public String getDumpSqlFormat() {
        return dumpSqlFormat;
    }

    public void setDumpSqlFormat(String dumpSqlFormat) {
        this.dumpSqlFormat = dumpSqlFormat;
    }

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }
}
